package com.childguo.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.childguo.Auth.JwtAuth;
import com.childguo.pojo.Stu;
import com.childguo.webResult.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class GlobalInterceptor implements HandlerInterceptor {
    @Value("${secret.login}")
    String secret_;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorized = request.getHeader("Authorization");
        if(StringUtils.hasLength(authorized)){
            try{
                Claim claim= new JwtAuth<>().decodeToken(authorized,"info");
                System.out.println("验证通过");
                return true;
            }catch(Exception e){
                System.out.println("验证失败"+e.getMessage());
                request.getRequestDispatcher("/login").forward(request, response);
                return false;
            }
        }else{
            System.out.println("Authorized为空，验证失败");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
